package com.zdp.oauth.filter;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zdp.oauth.common.JsonUtils;
import com.zdp.oauth.entity.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sesshomaru
 * @date 2022/5/23
 */
@Slf4j
@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 白名单
        if (checkWhiteListUrl(request.getRequestURI())) {
            return true;
        }

        String authorization = request.getHeader("Authorization");
        authorization = StrUtil.removePrefix(authorization, "Bearer ");

        if (StrUtil.isNotBlank(authorization)) {
            Jwt decode = JwtHelper.decode(authorization);
            String claims = decode.getClaims();
            LoginUserInfo loginUserInfo = JsonUtils.jsonToPojo(claims, LoginUserInfo.class);
            log.info("current login user info: \n [{}] ", JsonUtils.objectToPrettyJson(loginUserInfo));
            AccessContext.setLoginUserInfo(loginUserInfo);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /** 请求完全结束后调用afterCompletion 常用于清理资源等工作,统计请求耗时 */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (null != AccessContext.getLoginUserInfo()) {
            // 请求结束释放掉ThreadLocal防止内存泄漏
            AccessContext.clear();
        }
    }

    /**
     * <h2>校验是否是白名单接口，白名单接口直接放行不做验证token的过滤判断</h2>
     * */
    private boolean checkWhiteListUrl(String url) {

        // 这里是把swagger的访问url都给放行, 判断url是否有以下关键字
        return StringUtils.containsAny(url,
                "/user/user-info-by/authentication-center/check/token", "/error", "swagger", "v2",
                "webjars", "doc.html");
    }

}
